<template>
  <view>
    <view class="goods-list">
      <view class="goods-item" v-for="goods in goodsList" :key="goods.goods_id" @click="goToGoodsDetail(goods)">
        <view class="item-img">
          <image :src="goods.goods_small_logo || defaultPic" mode="heightFix"></image>
        </view>
        <view class="item-info">
          <view class="goods-name">{{goods.goods_name}}</view>
          <view class="goods-price">￥{{goods.goods_price | toFixed}}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        queryObj: {
          // 查询关键字
          query: '',
          // 商品分类id
          cid: '',
          // 页数
          pagenum: 1,
          // 每页长度
          pagesize: 10,
        },
        // 商品列表
        goodsList: [],
        total: 0,
        // 默认图片
        defaultPic: 'https://img3.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png'
      };
    },
    onLoad(options) {
      this.queryObj.query = options.query || '',
      this.queryObj.cid = options.cid || ''
      this.getGoodsList();
    },
    methods: {
      // 获取商品列表
      async getGoodsList() {
        const result = await uni.$http.get('/api/public/v1/goods/search', this.queryObj);
        if (result.data.meta.status !== 200) return $showMsg();
        this.goodsList = [...this.goodsList, ...result.data.message.goods];
        this.total = result.data.message.total;
      },
      // 跳转到商品详情
      goToGoodsDetail(goods) {
        uni.navigateTo({
          url: "/subpkg/goods_detail/goods_detail?goods_id=" + goods.goods_id
        })
      }
    },
    // 上拉触底加载更多
    onReachBottom() {
      // 判断是否还有数据
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('已经到底了');
      this.queryObj.pagenum += 1;
      this.getGoodsList();
    },
    // 下拉刷新
    onPullDownRefresh() {
      // 重置
      this.goodsList = [];
      this.queryObj.pagenum = 1;
      this.total = 0;
      this.getGoodsList();
      uni.stopPullDownRefresh();
    },
    filters: {
      toFixed(num) {
        return Number(num).toFixed(2)
      }
    }
  }
</script>

<style lang="scss">
  .goods-list {
    .goods-item {
      display: flex;
      padding: 10px 5px;
      border-bottom: 1px solid #f0f0f0;
      .item-img {
        width: 120px;
        height: 100px;
        margin-right: 10px;
        image {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .item-info {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .goods-name {
          font-size: 13px;
        }
        .goods-price {
          font-size: 16px;
          color: #C00000;
        }
      }
    }
  }
</style>
